package hhm.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Created by hhm on 2017/4/28.
 */
public class MyInvocationHandler implements InvocationHandler {
	private long settingTime;
	private Icallee obj;
	private int settingInvokeNum;
	private int realInvokeNum;

	public MyInvocationHandler(String time, final int settingInvokeNum, final Icallee obj) {
		this.settingInvokeNum = settingInvokeNum;
		this.settingTime = new Date(time).getTime();
		this.obj = obj;
		new Thread() {
			private boolean loop = true;

			@Override
			public void run() {
				while (loop) {
					if (new Date().getTime() > settingTime) {
						// 在这里可以做自己附加的操作
						obj.play();
						// 在这里可以做自己附加的操作
						loop = false;
					} else {
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}.start();

	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		if (method.getName().equals("run")) {
			realInvokeNum++;
			if (realInvokeNum >= settingInvokeNum) {
				result = method.invoke(obj, args);
				realInvokeNum = 0;
			}
		}
		return result;
	}
}